package com.eipp.android.redlonjohnson;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.DialogInterface;
import com.eipp.android.redlonjohnson.R;
import com.eipp.android.redlonjohnson.CustomHttpClient;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {
	EditText userId;   // To take birthyear as input from userdit
	EditText password;
	 Button submit; 
	 String returnString;
	 AlertDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		  .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
		  .penaltyLog().build());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		userId = (EditText) findViewById(R.id.editText1);
		password = (EditText) findViewById(R.id.editText2);
        submit = (Button) findViewById(R.id.login);
      
        submit.setOnClickListener(new View.OnClickListener(){        
            public void onClick(View v) {
             
            	// declare parextameters that are passed to PHP script i.e. the name "birthyear" and its value submitted by user   
             ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
             
             // define the parameter
            // postParameters.add(new BasicNameValuePair("userId",userId.getText().toString()));
            // postParameters.add(new BasicNameValuePair("passwordp", password.getText().toString()));
             postParameters.add(new BasicNameValuePair("Userid","11475"));
             postParameters.add(new BasicNameValuePair("passwordp", "Sailing1"));
             String response = null;
             
             // call executeHttpPost method passing necessary parameters 
             try {
            	 Log.i("karthiusha", "hi"); 
        response = CustomHttpClient.executeHttpPost(
          //"http://10.0.2.2/jsonscript.php", // your ip address if using localhost server
          "https://eipp03.com/redlon1/jsonscript.php",  // in case of a remote server
          postParameters);
        System.out.println("karthiusha ================= ");
        // store the result returned by PHP script that runs MySQL query
        String result = response.toString();  
        System.out.println("karthiusha ================= "+ result);
           Log.i("karthiusha", result);      
         //parse json data
            try{
                    returnString = "";
              JSONArray jArray = new JSONArray(result);
                    for(int i=0;i<jArray.length();i++){
                            JSONObject json_data = jArray.getJSONObject(i);
                            Log.i("log_kk","AccountNO: "+json_data.getInt("AccountNo")+
                                    ", UserName: "+json_data.getString("UserName")
                            );
                            //Get an output to the screen
                                                      	
                              returnString += "\n" + json_data.getInt("AccountNo") + " -> "+ json_data.getString("UserName");
                                Toast.makeText(getBaseContext(), json_data.getString("UserName") + " Login Sccuess", Toast.LENGTH_LONG).show();
                                Log.i("karthi", returnString);
                                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
                                Editor editor = pref.edit();
                                editor.putString("Userid", json_data.getString("Userid"));
                                editor.putInt("AccountNo", json_data.getInt("AccountNo"));
                                editor.putString("UserName", json_data.getString("UserName"));
                                editor.putString("Address", json_data.getString("Address"));
                                editor.commit();
							Intent intent = new Intent(getBaseContext(),MainActivity.class);
							startActivity(intent);
                            
                    }
            }
            catch(JSONException e){
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getBaseContext(), "Login Failed"+ userId.getText().toString() + " pass = "+password.getText().toString(), Toast.LENGTH_LONG).show();
                    
                    userId.setText("");
            }
        
            try{
            
            }
            catch(Exception e){
             Log.e("log_tag","Error in Display!" + e.toString());;          
            }   
       }
             catch (Exception e) {
        Log.e("log_tag","Error in http connection!!" + e.toString());     
       }
            }         
           });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.loginmenu, menu);
		return true;
	}

}
